package com.financing.wap.weixin.handle;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.wap.dto.DstArticleDTO;
import com.financing.wap.dto.DstUserInfoDTO;
import com.financing.wap.service.ICommonService;
import com.financing.wap.service.IDstArticleService;
import com.financing.wap.service.IDstUserArticleService;
import com.financing.wap.service.IDstUserInfoService;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.weixin.resp.Article;
import com.financing.wap.weixin.resp.NewsMessage;
import com.financing.wap.weixin.resp.TextMessage;
import com.financing.wap.weixin.util.MessageUtil;

/**
 * MsgType：text
 * 1 文本消息
 * @author lisu
 *
 */
@Service("textHandler")
public class TextHandler implements MessageHandler{

	Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IDstUserInfoService dstUserInfoService;

	@Autowired
	private IDstUserArticleService dstUserArticleService;
	
	@Autowired
	private IDstArticleService dstArticleService;

	@Autowired
	private ICommonService commonService;

	
	@Override
	public String messageHandler(Map<String, String> requestMap) {
		// 接收用户发送的文本消息内容
		final String content = requestMap.get("Content");
		// 发送方帐号（open_id）
		final String fromUserName = requestMap.get("FromUserName");
		// 公众帐号
		String toUserName = requestMap.get("ToUserName");
		String resultContext = "";
		Date date = new Date();
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(date.getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);
		
		String msgId = requestMap.get("MsgId");
		// 重复处理  临时处理返回：休眠5秒  后续去重处理 
		Object obj=MemcacheCacheHelper.mcc.get(msgId);
		logger.info("msgId:"+msgId);
		//微信解析时长  多少毫秒内不重复解析
		long wxParseMs=5000L;
		if(obj!=null){
			Date d=(Date)obj;
			if(date.getTime()-d.getTime()<wxParseMs){
				try {
					Thread.sleep(10000);
				} catch (Exception e) {
				}
			}
			// 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
			textMessage.setContent("解析中，稍后在获客文章“我的”中查看");
			// 将文本消息对象转换成xml字符串
			return MessageUtil.textMessageToXml(textMessage);
		}
		//5秒钟失效 
		MemcacheCacheHelper.mcc.set(msgId,date,DateUtil.addMillisecond(date,wxParseMs));
		
		String regex = "https?://.*?";
		if (content.matches(regex)) {
			logger.info("拦截到地址:处理为可用文章..");
			if (content.contains("mp.weixin.qq.com")||content.contains("work.weixin.qq.com")) {
				// 创建图文消息
				 NewsMessage newsMessage = new NewsMessage();
				 newsMessage.setToUserName(fromUserName);
				 newsMessage.setFromUserName(toUserName);
				 newsMessage.setCreateTime(date.getTime());
				 newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
				 newsMessage.setFuncFlag(0);
				 newsMessage.setArticleCount(1);
				 List<Article> articles=new ArrayList<Article>();
				try {
					Map<String,String> map = new HashMap<String, String>();
					map.put("content",content);
                    DstUserInfoDTO userInfoDTO = new DstUserInfoDTO();
                    userInfoDTO.setUserWechatOpenid(fromUserName);
                    userInfoDTO =  dstUserInfoService.queryListGetFirst(userInfoDTO);
					map.put("fromUserName",fromUserName);
                    map.put("userName",userInfoDTO.getUserName());
                    map.put("articleStatus","1");//0：待上架，1 ：已上架
                    map.put("resource","2");//文章来源1后台上传2用户所属
                    map.put("wxpathurl", content);
                    
					DstArticleDTO articleDTO =commonService.createArticle(map);
					//用户绑定文章地址
					Article e=new Article();
					e.setTitle(articleDTO.getTitle());
					e.setPicUrl(map.get("imageThumbnail"));
					e.setDescription(articleDTO.getDescription());
					e.setUrl(articleDTO.getUrl());
					articles.add(e);
				} catch (Exception e1) {
					logger.info("query user info error", e1);
				}
				newsMessage.setArticles(articles);
				return MessageUtil.newsMessageToXml(newsMessage);
			} else {
				resultContext = "暂时不支持解析非公众号文章!";
			}
		}else{
			resultContext = "非公众号文章!";
		}
		// 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
		textMessage.setContent(resultContext);
		
		try {
			MemcacheCacheHelper.mcc.delete(msgId);
		} catch (Exception e) {
			logger.info("remove msgId error", e);
		}
		// 将文本消息对象转换成xml字符串
		return MessageUtil.textMessageToXml(textMessage);
	}

	@Override
	public void messageSubsequentHandler(Map<String, String> requestMap) {
	}

}
